package com.wz.datachannel.view;

import java.io.File;
import java.util.ArrayList;

import com.alibaba.fastjson.JSONObject;
import com.wz.datachannel.R;
import com.wz.datachannel.model.UserInfo;
import com.wz.datachannel.netty.WzDataChannelHelper;
import com.wz.datachannel.netty.WzDataChannelHelper.ICallBackUpdateUserInfo;
import com.wz.datachannel.netty.WzDataChannelHelper.SerConnStatus;
import com.wz.datachannel.service.MainService;
import com.wz.datachannel.util.ToastUtil;
import com.wzfile.upload.WzUpload;
import com.wzfile.upload.WzUpload.OnUploadListener;
import com.wzfile.upload.WzUpload.RequestDownCardResult;
import com.wzfile.upload.WzUpload.UpLoadKeyErrorException;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class UpdateActivity extends BaseActivity implements OnClickListener {

	PhotoEditView editPotoView1;
	ViewGroup	  gState,gContent;
	String		  uploadkey = null;
	UserInfo 	  userInfo  = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setAllowWindowMove(true, false);
		
		WzDataChannelHelper dataChannel = MainService.getDataChannel();
		if (dataChannel!=null && dataChannel.getConnStatus() == SerConnStatus.LOGIN_OK){
			//已登录
			userInfo = dataChannel.getUserInfo();
			if (userInfo==null){
				showToastText("用户信息无效！");
				finish();
				return;
			}
			uploadkey = dataChannel.getFileUploadKey();
			if (uploadkey==null){
				showToastText("上传服务无法启动！");
				finish();
				return;
			}
		}else{
			//未登录
			finish();
			return;
		}
		
		
		//当前已成功登录:		
		setContentView(R.layout.activity_update);		
		
		initUserInfo(userInfo.getUserid(),userInfo.getUsername(),userInfo.getPhoto());
		
		if (getIntent().getStringExtra("uploadkey")!=null){
			uploadkey = getIntent().getStringExtra("uploadkey");
		}
				
		editPotoView1 = (PhotoEditView)findViewById(R.id.editPotoView1);	
		editPotoView1.setVisibility(View.INVISIBLE);

		gState   = (ViewGroup)findViewById(R.id.gState);
		gContent = (ViewGroup)findViewById(R.id.gContent);
		
		gState.setVisibility(View.INVISIBLE);
		
		findViewById(R.id.button_fangda).setOnClickListener(this);
		findViewById(R.id.button_suoxiao).setOnClickListener(this);
		findViewById(R.id.button_yes).setOnClickListener(this);
		findViewById(R.id.button_no).setOnClickListener(this);
		findViewById(R.id.button_zhaopian).setOnClickListener(this);
		findViewById(R.id.button_paizhao).setOnClickListener(this);
		
		new File(Environment.getExternalStorageDirectory().getPath() + "/temp/").mkdirs();
	} 
	
	@Override 
	public void onClick(View v) {
		// TODO Auto-generated method stub		
		try{
			switch(v.getId()){
			case R.id.button_fangda:
				editPotoView1.updateZoom(0.1f);
				break;
			case R.id.button_suoxiao:
				editPotoView1.updateZoom(-0.1f);
				break;		
			case R.id.button_yes:
				startUpdatePhoto();
				break;
			case R.id.button_no:
				editPotoView1.close();
				finish();
				break;				
			case R.id.button_zhaopian:			
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, 1);
				break;
			case R.id.button_paizhao:
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg")));  
	            startActivityForResult(i, 2);   
				break;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 初始化用户资料
	 * @param userid
	 * @param username
	 * @param userphoto
	 */
	private void initUserInfo(String userid,String username,String userphoto){
		TextView tv = (TextView)findViewById(R.id.textViewUsername);		
		tv.setText(username);
		tv = (TextView)findViewById(R.id.textViewUserid);
		tv.setText(userid);		
		//findViewById(R.id.imageViewUserPhoto);
	}
	
	private boolean isupdatephoto = false;
	
	private void startUpdatePhoto(){
		
		if (isupdatephoto) return;
		
		if (!editPotoView1.isOpen()){
			showToastText("请先选择要使用的图片!");
			return;
		}
		String filename = Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_photo.jpg";
		if (!editPotoView1.takeImageToFile(filename)){
			//截取头像失败，请选择文件
			showToastText("提取头像出错，请重新选择图片!");
			return;
		}
		
		isupdatephoto = true;		
		gContent.setVisibility(View.INVISIBLE);
		gState.setVisibility(View.VISIBLE);
		
		try {
			WzUpload upload = WzUpload.getUpload(uploadkey);
			
			upload.setOnUploadListener(new OnUploadListener() {
				
				@Override
				public void OnUpload(String arg0, long arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void OnSucess(String arg0, RequestDownCardResult arg1) {
					// TODO Auto-generated method stub
					//上传成功
					try{
						updateUserPhotoInfo(arg1.getFileList()[0].getFileAddr());
					}catch(Exception e){
						showToastText("上传头像时发生错误，请稍后重试!");
						gotoContent();
					}					
				}
				 
				@Override
				public void OnStop(String arg0, int arg1, String arg2) {
					// TODO Auto-generated method stub
					showToastText("头像上传失败:" + arg2);
					gotoContent();
				}
				
				@Override
				public void OnStart(String arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void OnProgress(String arg0, int arg1, long arg2, long arg3) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void OnLoading(String arg0) {
					// TODO Auto-generated method stub
					
				}
			});
			
			ArrayList<File> files = new ArrayList<File>(); 
			files.add(new File(filename));
			upload.start(files,"upload");
			
		} catch (UpLoadKeyErrorException e) {
			showToastText("操作失败,请稍后再试.");
			gotoContent();
		}
		
	}
	
	private void updateUserPhotoInfo(String url){
		
		//此处添加用户资料的处理过程:
		WzDataChannelHelper dataChannel = MainService.getDataChannel();
		if (dataChannel!=null && dataChannel.getConnStatus() == SerConnStatus.LOGIN_OK){
			JSONObject params = new JSONObject();
			params.put("photo", url);
			final Handler handler = new Handler(){
				@Override
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					switch(msg.what){
					case 1:
						sucess();
						break;
					case 0:
						showToastText("修改资料失败：" + msg);
						gotoContent();
						break;
					case -1:
						showToastText("请求处理超时，请稍后重试！");
						gotoContent();
						break;
					}
				}				
			};
			
			if (dataChannel.updateUserInfo(params.toJSONString(),new ICallBackUpdateUserInfo() {
				
				@Override
				public void OnTimeOut() {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(-1);
				}
				
				@Override
				public void OnSucess() {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(1);
				}
				
				@Override
				public void OnFail(String msg) {
					// TODO Auto-generated method stub
					Message m = new Message();
					m.what = 0;
					m.obj = msg;
					handler.sendMessage(m);
				}
				 
			}) != 1){
				//请求失败:
				showToastText("请稍后重试！");
				gotoContent();
			}
			
		}else{
			showToastText("您已下线，请上线后再试！");
			gotoContent();
		}
		
	}
	
	private void sucess(){
		showToastText("修改头像成功！");
		finish();
	}
	
	private void gotoContent(){
		gContent.setVisibility(View.VISIBLE);
		gState.setVisibility(View.INVISIBLE);
		isupdatephoto = false;		
	}
	
	@SuppressWarnings("unused") 
	private void showStateText(String text){ 
		TextView tv = (TextView)findViewById(R.id.textViewState);
		tv.setText(text);
	}
	
	private void showToastText(String text){
		ToastUtil.toastShowLong(getApplication(), text);
	}
	
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		super.onActivityResult(requestCode, resultCode, data);		
		try{
			switch(requestCode){
				case 1:
				{
					//选择图片
					if (resultCode == RESULT_OK){
						String name = data.getDataString();					
						Uri uri = Uri.parse(name);
						String filename = "";
						if (!name.startsWith("file:///")) { 
							String[] proj = { MediaStore.Images.Media.DATA };
							@SuppressWarnings("deprecation")
							Cursor actualimagecursor = managedQuery(uri, proj, null,null, null);
							int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
							actualimagecursor.moveToFirst();
							filename = actualimagecursor.getString(actual_image_column_index);
						} else {
							filename = name;
							try {
								filename = name.substring(name.lastIndexOf("///") + 2);
							} catch (Exception e) {
							}					
						}			
						editPotoView1.openImageFile(filename);
					}
					break;
				}case 2:{
					//拍照  
					if (resultCode == RESULT_OK){
						editPotoView1.openImageFile(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg");		
						new File(Environment.getExternalStorageDirectory().getPath() + "/temp/wzim_capture.jpg").delete();
					}
					break;
				}
			}
			
		}catch(Exception e){
				;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		editPotoView1.close();
		super.onDestroy();
	}

}
